package com.sunnyweather.android.logic.util

import kotlinx.coroutines.suspendCancellableCoroutine
import retrofit2.*
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

suspend fun <T : Any> Call<T>.awaitTest(): T {
    return suspendCancellableCoroutine { continuation ->
        continuation.invokeOnCancellation {
            cancel()
        }
        enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                if (response.isSuccessful) {
                    val body = response.body()
                    if (body == null) {
                        val invocation = call.request().tag(Invocation::class.java)!!
                        val method = invocation.method()
                        val e = KotlinNullPointerException("Response from " +
                                method.declaringClass.name +
                                '.' +
                                method.name +
                                " was null but response body type was declared as non-null")
                        LogUtil.e("awaitTest body=null",e.toString())
                        continuation.resumeWithException(e)
                    } else {
                        LogUtil.d("awaitTest body!=null",body.toString())
                        continuation.resume(body)
                    }
                } else {
                    LogUtil.d("awaitTest request failed",response.toString())
                    continuation.resumeWithException(HttpException(response))
                }
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                LogUtil.e("awaitTest onFailure",t.toString())
                continuation.resumeWithException(t)
            }
        })
    }
}